package org.net.cms.filter;

import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.net.cms.service.parentaccount.ParentAccountService;
import org.net.cms.uitl.JwtUtil;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
@Slf4j
public class JwtFilter extends OncePerRequestFilter {

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private ParentAccountService parentAccountService;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String authorization = request.getHeader("Authorization");
        String token = null;

        if (authorization != null && authorization.startsWith("Bearer ")) {
            token = authorization.substring(7).trim();
        }

        if (token != null && !token.isEmpty() && jwtUtil.checkToken(token)) {
            try {
                Claims claims = jwtUtil.getTokenBody(token);
                String phone = (String) claims.get("phone");
                UserDetails userDetails = parentAccountService.loadUserByUsername(phone);

                if (phone != null) {
                    UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    SecurityContextHolder.getContext().setAuthentication(auth);
                }
            } catch (Exception e) {
                log.error(e.getMessage());
                System.out.println("查询出错");
            }
        } else if (!isPermitAllRequest(request)) {
            // 只有不是permitAll的路径才会打印警告
            log.warn("token为null\\为空\\已过期");

        }
        filterChain.doFilter(request, response);
    }

    // 判断是否是 permitAll 的请求（即不需要 token 的路径）
    private boolean isPermitAllRequest(HttpServletRequest request) {
        String method = request.getMethod();
        String uri = request.getRequestURI();

        // 匹配 POST /admin/application/status
        if ("POST".equals(method)) {
            if ("/admin/application/status".equals(uri) || "/app/account/check".equals(uri) || "/admin/application/list".equals(uri) || "/admin/user/login".equals(uri)) {
                return true;
            }
        }
        return false;
    }

    // 关键：跳过这些路径的过滤器执行
    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        return isPermitAllRequest(request);
    }
}
